package edu.ccut.saturn.component.utils;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;

public class FreemarkerUtils {
	private static Configuration freemarkerCfg;
	private static final String ENCODING = "UTF-8";
	
	static {
		init();
	}
	
	private FreemarkerUtils() {
	}
	
	private static void init() {
		freemarkerCfg = new Configuration();
		TemplateLoader[] loaders = {new ClassTemplateLoader(FreemarkerUtils.class, File.separator)};
		freemarkerCfg.setTemplateLoader(new MultiTemplateLoader(loaders));
		freemarkerCfg.setDefaultEncoding(ENCODING);
	}

	public static void writeTemplate(String templateUrl, Map<String, ?> value, Writer writer) {
		try {
			Template template = freemarkerCfg.getTemplate(templateUrl);
			template.setEncoding(ENCODING);
			
			template.process(value, writer, ObjectWrapper.BEANS_WRAPPER);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				writer.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void writeTemplateToFile(String templateUrl, Map<String, ?> value, String path) {
		Writer writer = null;
		
		File file = SaturnFileUtils.getFile(path);
		
		try {
			writer = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(file), ENCODING));
			
			writeTemplate(templateUrl, value, writer);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
